package com.example.day10.homework;

import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class CsvPrintEmp {
    public static void main(String[] args) throws IOException, IllegalAccessException {
        String[] titles=new String[]{"员工编号","姓名","性别","入职时间","所在部门","薪资"};
        String[]  propertys=new String[]{"id","name","gender","date","department","salary"};

        Employee e1=new Employee(1001,"Sam",0,"20170203","研发部",28000.00);
        Employee e2=new Employee(1002,"Tommy",0,"20160305","销售部",4000.00);
        Employee e3=new Employee(1003,"Sandy",1,"120170203","研发部",9000.00);
        Employee e4=new Employee(1004,"Ada",1,"20160305","行政部",6000.00);
        Employee e5=new Employee(1005,"Lynn",0,"20170203","销售部",5000.00);
        Employee e6=new Employee(1006,"Yigo",0,"20190605","研发部",9000.00);
        Employee e7=new Employee(1007,"Walter",1,"120160203","销售部",5600.00);
        Employee e8=new Employee(1008,"Pinkman",1,"20160914","研发部",9800.00);

        List list=new ArrayList();
        list.add(e1);
        list.add(e2);
        list.add(e3);
        list.add(e4);
        list.add(e5);
        list.add(e6);
        list.add(e7);
        list.add(e8);
        
        exportCsv(titles,propertys,list);


    }

    private static void exportCsv(String[] titles, String[] propertys, List list) throws IOException, IllegalAccessException {
        File file=new File("src/com/example/day10/homework/emply.csv");
        //构建输出流，同时指定编码
        OutputStreamWriter owriter= new OutputStreamWriter(new FileOutputStream(file),"gbk");
        //csv文件是逗号分隔，除第一个外，每次写入一个单元格数据后需要输入逗号
        for (String title : titles) {
            owriter.write(title);
            owriter.write(",");
        }
        //写完头部文件之后换行
        owriter.write("\r\n");
        //书写集合中的内容
        for (Object obj : list) {
            //利用反射获取所有字段
            Field[] fields=obj.getClass().getDeclaredFields();
            for (String property : propertys) {
                for (Field field : fields) {
                    //设置可见性
                    field.setAccessible(true);
                    if(property.equals(field.getName())){
                        owriter.write(field.get(obj).toString());
                        owriter.write(",");
                        continue;
                    }
                }
            }
            //写完一行后换行
            owriter.write("\r\n");
        }
        owriter.flush();
        owriter.close();

    }
}
